package rensoft.android;

import android.os.Bundle;
import rensoft.java.collections.Map;
import rensoft.java.event.Event.EventRegistration;
import rensoft.java.event.Listener;

public abstract class HasActivityPresenter extends ActivityPresenter {

  private boolean active = true;

  public HasActivityPresenter(HasActivity hasActivity) {
    super(hasActivity.activity());
    hasActivity.getOnPause().attach(new Listener<Void>() {
      public void onEvent(EventRegistration registration, Void arg) {
        if (isActive()) onPause();
      }
    });
    hasActivity.getOnStart().attach(new Listener<Void>() {
      public void onEvent(EventRegistration registration, Void arg) {
        if (isActive()) onStart();
      }
    });
    hasActivity.getOnStop().attach(new Listener<Void>() {
      public void onEvent(EventRegistration registration, Void arg) {
        if (isActive()) onStop();
      }
    });
    hasActivity.getOnCreate().attach(new Listener<Bundle>() {
      public void onEvent(EventRegistration registration, Bundle bundle) {
        if (isActive()) onCreate(bundle);
      }
    });
    hasActivity.getOnSaveInstance().attach(new Listener<Bundle>() {
      public void onEvent(EventRegistration registration, Bundle bundle) {
        if (isActive()) onSaveInstanceState(bundle);
      }
    });
    hasActivity.getOnRetainNonConfigurationInstance().attach(new Listener<Map<String, Object>>() {
      public void onEvent(EventRegistration registration, Map<String, Object> arg) {
        if (isActive()) onRetainNonConfigurationInstance(arg);
      }
    });
    hasActivity.getOnRestoreNonConfigurationInstance().attach(new Listener<Map<String, Object>>() {
      public void onEvent(EventRegistration registration, Map<String, Object> arg) {
        if (isActive()) onRestoreNonConfigurationInstance(arg);
      }
    });
    hasActivity.getOnActivityResult().attach(new Listener<ActivityResult>() {
      public void onEvent(EventRegistration registration, ActivityResult arg) {
        if (isActive()) onActivityResult(arg.requestCode, arg.resultCode, arg.data);
      }
    });
    hasActivity.getOnResume().attach(new Listener<Void>() {
      public void onEvent(EventRegistration registration, Void arg) {
        if (isActive()) onResume();
      }
    });
    hasActivity.getOnDestroy().attach(new Listener<Void>() {
      public void onEvent(EventRegistration registration, Void arg) {
        onDestroy();
      }
    });
  }

  protected void setActive(boolean active) {
    this.active = active;
  }

  private boolean isActive() {
    return active;
  }
}
